package SceneTrigger

import (
	. "GameLogic/Scene"
	"misc/Clojure"
	"misc/Clojure/parse"
	log "misc/seelog"
)

type SceneTrigger struct {
	Scene *Scene

	curTrID        int
	Triggers       []*Trigger
	Events         map[string][]*Trigger
	clojureContext *Clojure.Context
}

func NewSceneTrigger(scene *Scene) ISceneTrigger {
	retSceneTrigger := &SceneTrigger{
		Events:   make(map[string][]*Trigger),
		Triggers: make([]*Trigger, 0),
		Scene:    scene,
	}
	retSceneTrigger.clojureContext = Clojure.NewContext(Clojure.MainContext)
	retSceneTrigger.clojureContext.Import(Clojure.MainContext, "")

	retSceneTrigger.clojureContext.Define("CurScene", &parse.ObjectNode{Val: scene})

	return retSceneTrigger
}

func (st *SceneTrigger) Init() {
	st.clojureContext.Define("players-count", &parse.NumberNode{Val: len(st.Scene.GamePlayers)})
	Clojure.EvaluateTree(Clojure.GetAstTree("Trigger"), st.clojureContext)
}

func (st *SceneTrigger) OnLoad() {
	st.CallEvent("GameLoad", nil)
}

func (st *SceneTrigger) AddTrigger(tri *Trigger) {
	st.Triggers = append(st.Triggers, tri)
	tri.ID = st.curTrID
	st.curTrID++

	for i := 0; i < len(tri.Events); i++ {
		eName := tri.Events[i].GetEventInfo().EventName
		_, ok := st.Events[eName]
		if !ok {
			st.Events[eName] = make([]*Trigger, 0)
		}
		st.Events[eName] = append(st.Events[eName], tri)
	}
}

func (st *SceneTrigger) CallEvent(eventName string, triggerUnit IUnit, args ...interface{}) {
	elist, ok := st.Events[eventName]
	if !ok {
		log.Info("GameTrigger Call not have Event " + eventName)
		return
	}
	for i := 0; i < len(elist); i++ {
		elist[i].OnTrigger(triggerUnit)
	}

}

func (st *SceneTrigger) Update() {
	for i := 0; i < len(st.Triggers); i++ {
		st.Triggers[i].Update()
	}
}
